import router from '@/router'
import { ElMessage } from 'element-plus'
import { Box } from '@element-plus/icons-vue'

const rolePermissions = {
    admin: ['admin-dashboard', 'admin-elder', 'admin-meal', 'admin-accident', 'admin-checkin', 'admin-medicine', 'admin-family', 'admin-outing', 'admin-user', 'admin-outing-return', 'admin-medical', 'admin-announcement', 'admin-profile'],
    caregiver: ['caregiver-dashboard', 'caregiver-elder', 'caregiver-meal', 'caregiver-accident', 'caregiver-medicine-receive', 'caregiver-medical', 'caregiver-messages', 'caregiver-photo-upload', 'caregiver-outing', 'caregiver-profile'],
    reception: ['reception-dashboard', 'reception-checkin', 'reception-outing', 'reception-visitor', 'reception-bed', 'reception-caregiver', 'reception-messages', 'reception-announcement', 'reception-carousel', 'reception-consult', 'reception-profile'],
    family: ['family-dashboard', 'family-elder', 'family-outing', 'family-outing-return', 'family-meal', 'family-photos', 'family-accident', 'family-medical', 'family-messages', 'family-profile']
}

router.beforeEach((to, from, next) => {
    const userInfoStr = localStorage.getItem('userInfo')
    const userInfo = userInfoStr ? JSON.parse(userInfoStr) : {}
    const role = userInfo.role || 'unknown'
    const allowedRoutes = rolePermissions[role] || []

    console.log('权限验证 - 当前路径:', to.path)
    console.log('权限验证 - 用户信息:', userInfo)
    console.log('权限验证 - 用户角色:', role)
    console.log('权限验证 - 允许的路由:', allowedRoutes)

    // 允许未登录用户访问欢迎页面、登录页面和注册页面
    const publicPages = ['/', '/welcome', '/login', '/register']
    
    // 如果访问的是公开页面，直接允许
    if (publicPages.includes(to.path)) {
        console.log('权限验证 - 公开页面，直接允许')
        next()
        return
    }

    // 如果用户未登录且访问的不是公开页面，跳转到欢迎页面
    if (!userInfo.name) {
        console.log('权限验证 - 用户未登录，跳转到欢迎页面')
        next('/welcome')
        return
    }

    // 如果用户已登录但访问登录或注册页面，跳转到对应角色的仪表板
    if (userInfo.name && (to.path === '/login' || to.path === '/register')) {
        const roleRoutes = {
            'caregiver': '/dashboard/caregiver-dashboard',
            'family': '/dashboard/family-dashboard',
            'admin': '/dashboard/admin-dashboard',
            'reception': '/dashboard/reception-dashboard'
        }
        const targetRoute = roleRoutes[role] || '/dashboard/caregiver-dashboard'
        next(targetRoute)
        return
    }

    // 角色专属首页跳转
    if (to.path === '/dashboard') {
        const roleRoutes = {
            'caregiver': '/dashboard/caregiver-dashboard',
            'family': '/dashboard/family-dashboard',
            'admin': '/dashboard/admin-dashboard',
            'reception': '/dashboard/reception-dashboard'
        }
        const targetRoute = roleRoutes[role] || '/dashboard/caregiver-dashboard'
        next(targetRoute)
        return
    }

    // 检查权限
    const page = to.path.split('/')[1] // /elder -> elder
    const fullPath = to.path // 完整路径
    
    // 特殊处理仪表板页面权限
    const dashboardPages = [
        '/dashboard/caregiver-dashboard',
        '/dashboard/family-dashboard', 
        '/dashboard/admin-dashboard',
        '/dashboard/reception-dashboard'
    ]
    
    // 如果是仪表板页面，检查是否有对应的权限
    if (dashboardPages.includes(fullPath)) {
        const dashboardType = fullPath.split('/').pop() // caregiver-dashboard, family-dashboard, etc.
        
        // 简化权限检查：如果用户已登录且访问的是对应角色的仪表板，直接允许
        const roleDashboardMap = {
            'caregiver': '/dashboard/caregiver-dashboard',
            'family': '/dashboard/family-dashboard',
            'admin': '/dashboard/admin-dashboard',
            'reception': '/dashboard/reception-dashboard'
        }
        
        const expectedDashboard = roleDashboardMap[role]
        
        // 如果用户访问的是自己角色的仪表板，直接允许
        if (fullPath === expectedDashboard) {
            console.log('权限验证 - 访问自己角色的仪表板，允许访问')
            next()
            return
        }
        
        // 如果用户有访问该仪表板的权限，允许访问
        if (allowedRoutes.includes(dashboardType)) {
            console.log('权限验证 - 有权限访问该仪表板，允许访问')
            next()
            return
        }
        
        // 如果用户没有权限访问该仪表板，跳转到自己的仪表板
        console.log('权限验证 - 无权限访问该仪表板，跳转到自己的仪表板')
        const fallbackRoute = roleDashboardMap[role] || '/dashboard/caregiver-dashboard'
        // 避免循环重定向
        if (to.path !== fallbackRoute) {
            next(fallbackRoute)
        } else {
            next()
        }
        return
    }
    
    // 普通页面权限检查 - 修复权限检查逻辑
    // 检查是否在允许的路由中
    const routeName = to.name || to.path.split('/').pop()
    
    // 改进的权限检查逻辑
    let hasPermission = false
    
    // 方法1: 检查路由名称（主要方法）
    if (allowedRoutes.includes(routeName)) {
        hasPermission = true
    }
    
    // 方法2: 检查路径的最后部分
    const pathParts = to.path.split('/')
    const lastPathPart = pathParts[pathParts.length - 1]
    if (allowedRoutes.includes(lastPathPart)) {
        hasPermission = true
    }
    
    // 方法3: 检查完整路径是否包含允许的路由
    for (const allowedRoute of allowedRoutes) {
        if (to.path.includes(allowedRoute)) {
            hasPermission = true
            break
        }
    }
    
    // 特殊处理个人中心页面 - 所有角色都可以访问
    if (to.path.includes('/profile')) {
        hasPermission = true
    }
    
    // 特殊处理角色专属页面
    const roleSpecificPaths = {
        'caregiver': ['/dashboard/caregiver/'],
        'family': ['/dashboard/family/'],
        'admin': ['/dashboard/admin/'],
        'reception': ['/dashboard/reception/']
    }
    
    // 如果访问的是对应角色的专属页面，检查权限
    if (roleSpecificPaths[role] && roleSpecificPaths[role].some(path => to.path.startsWith(path))) {
        // 构建完整的路由名称，例如 /dashboard/caregiver/elder -> caregiver-elder
        const pagePath = to.path.replace('/dashboard/', '')
        const pageName = pagePath.replace(/\//g, '-')
        if (allowedRoutes.includes(pageName)) {
            hasPermission = true
        }
    }
    
    // 特殊处理向后兼容的旧路由
    const legacyRouteMap = {
        'elder': ['caregiver-elder', 'family-elder', 'admin-elder'],
        'meal': ['caregiver-meal', 'family-meal', 'admin-meal'],
        'accident': ['caregiver-accident', 'family-accident', 'admin-accident'],
        'checkin': ['admin-checkin', 'reception-checkin'],
        'medicine': ['admin-medicine'],
        'family': ['admin-family'],
        'outing': ['caregiver-outing', 'family-outing', 'admin-outing', 'reception-outing'],
        'outing-return': ['family-outing-return', 'admin-outing-return'],
        'medical': ['caregiver-medical', 'family-medical', 'admin-medical'],
        'messages': ['caregiver-messages', 'family-messages', 'reception-messages'],
        'user': ['admin-user'],
        'announcement': ['admin-announcement', 'reception-announcement']
    }
    
    // 检查旧路由是否有权限
    if (legacyRouteMap[routeName]) {
        const allowedLegacyRoutes = legacyRouteMap[routeName]
        for (const legacyRoute of allowedLegacyRoutes) {
            if (allowedRoutes.includes(legacyRoute)) {
                hasPermission = true
                break
            }
        }
    }
    
    if (hasPermission) {
        console.log('权限验证 - 有权限访问页面:', to.path)
        next()
    } else {
        console.log('权限验证 - 无权限访问页面:', to.path, '允许的路由:', allowedRoutes)
        ElMessage.error('无权限访问该页面')
        // 根据角色跳转到对应的首页
        const roleRoutes = {
            'caregiver': '/dashboard/caregiver-dashboard',
            'family': '/dashboard/family-dashboard',
            'admin': '/dashboard/admin-dashboard',
            'reception': '/dashboard/reception-dashboard'
        }
        const fallbackRoute = roleRoutes[role] || '/dashboard'
        // 避免循环重定向
        if (to.path !== fallbackRoute) {
            next(fallbackRoute)
        } else {
            next()
        }
    }
})
